<template>
    <van-sticky>
        <van-card class="van-card-header"
                  :title="user.userNickname"
                  :thumb="user.userHeadImg"
                  :price="(user.address === null ? '未知' : Number(user.address.province) === 0 ? '内网' : user.address.province) + user.address.equipmentType + '在线'"
                  currency
                  num
        >
            <template #num>
                <van-popover v-model:show="showPopover" :actions="actions" @select="onSelect" placement="bottom-end">
                    <template #reference>
                        <span style="color: white; font-size: 30px">+</span>
                    </template>
                </van-popover>
            </template>
        </van-card>
    </van-sticky>
    <van-search
            v-model="searchContent"
            shape="round"
            clearable
            show-action
            @cancel="searchUserChatList"
            @search="onSearch"
            @blur="onSearch"
            background="#F2F2F2"
            placeholder="搜索好友"
            input-align="center"
    />

    <div v-if="tabbarActive === 0" v-for="item in chatFriendList" :key="item">
        <hr/>
        <van-swipe-cell class="delete-button">
            <van-card
                    v-if="item.topStatus === 1"
                    style="background-color: #f2f3f5"
                    :title="item.userNickname"
                    :thumb="item.userHeadImg"
                    :desc="item.lastMessage"
                    :tag="item.unreadMessageCount === 0 ? '' : (item.unreadMessageCount > 100 ? '99+' : (item.unreadMessageCount > 1000 ? '999+' : item.unreadMessageCount + ''))"
                    @click="toChatWith(item.userId)"
            >
                <template #num>
                    {{ item.lastMessageTime }}
                </template>
            </van-card>
            <van-card v-else
                      :title="item.userNickname"
                      :thumb="item.userHeadImg"
                      :desc="item.lastMessage"
                      :tag="item.unreadMessageCount === 0 ? '' : (item.unreadMessageCount > 100 ? '99+' : (item.unreadMessageCount > 1000 ? '999+' : item.unreadMessageCount + ''))"
                      @click="toChatWith(item.userId)"
            >
                <template #num>
                    {{ item.lastMessageTime }}
                </template>
            </van-card>
            <template #right>
                <van-button v-if="item.topStatus === 0" square text="置顶" type="primary"
                            @click="changeToTopStatus(item.userId)" class="delete-button"/>
                <van-button v-if="item.topStatus === 1" square text="取消置顶" type="primary"
                            @click="changeToTopStatus(item.userId)" class="delete-button"/>
                <van-button square text="删除" type="danger" @click="changeChatListDeleteStatus(item.userId)"
                            class="delete-button"/>
            </template>
        </van-swipe-cell>
    </div>
    <hr/>

    <van-tabs
            v-if="tabbarActive === 1"
            v-model:active="tabActive"
            @change="tabOnChange"
    >
        <van-tab title="好友">
            <van-cell is-link @click="newFriendCellClick" v-if="haveNewFriend">
                <template #title>
                    <van-tag class="custom-title" type="danger">新朋友</van-tag>
                </template>
            </van-cell>
            <div v-for="item in friendList" :key="item">
                <van-card
                        :title="item.userNickname"
                        :thumb="item.userHeadImg"
                        desc="这里是签名"
                        @click="toChatWith(item.userId)"
                />
                <hr/>
            </div>
        </van-tab>
        <van-tab title="群聊">群聊</van-tab>
    </van-tabs>

    <van-tabbar v-model="tabbarActive" @change="tabbarOnChange">
        <van-tabbar-item v-if="messageTotalNumber > 0" icon="chat" :badge="messageTotalNumber">消息</van-tabbar-item>
        <van-tabbar-item v-else icon="chat">消息</van-tabbar-item>
        <van-tabbar-item icon="friends-o" dot>联系人</van-tabbar-item>
    </van-tabbar>
</template>
<script>
import {router} from "@/router";
import {Notify, Toast} from "vant";
import {
    whetherHaveNewFriend,
    searchUserFriend,
    searchUserChatList,
    changeToTopStatus,
    changeChatListDeleteStatus,
    searchFriend
} from "@/api/friend";
import {initWebSocket, websocketReadyState, getSock} from "@/util/socket"

export default {
    name: "home",
    data() {
        return {
            user: {},
            searchContent: '',
            tabbarActive: 0,
            tabActive: 0,
            messageTotalNumber: 0,
            showPopover: false,
            actions: [
                {id: 1, text: '添加好友', icon: 'add-o'},
                {id: 2, text: '新建群聊', icon: 'new-o'},
            ],
            haveNewFriend: false,
            friendList: [],
            chatFriendList: [],
        }
    },
    methods: {
        onSearch() {
            let requestParam = {
                'username': this.searchContent,
                'userId': this.user.userId
            }
            searchFriend(requestParam).then(response => {
                if (response.code === 200) {
                    this.chatFriendList = response.data
                    response.data.forEach(item => {
                        this.messageTotalNumber += item.unreadMessageCount
                        if (this.messageTotalNumber > 100) {
                            this.messageTotalNumber = '99+'
                        } else if (this.messageTotalNumber > 1000) {
                            this.messageTotalNumber = '999+'
                        }
                    })
                    this.searchContent = ''
                }
            })
        },
        onSelect(action) {
            if (action.id === 1) {
                router.push({path: "/search"})
            }
        },
        tabbarOnChange() {
            if (this.tabbarActive === 0) {
                this.searchUserChatList()
            } else {
                this.whetherHaveNewFriend()
                this.searchUserFriend()
            }
        },
        tabOnChange(index) {
            if (index === 0) {
                this.whetherHaveNewFriend()
                this.searchUserFriend()
            }
        },
        whetherHaveNewFriend() {
            whetherHaveNewFriend(this.user.userId).then(response => {
                if (response.code === 200) {
                    this.haveNewFriend = response.data
                }
            })
        },
        searchUserFriend() {
            searchUserFriend(this.user.userId).then(response => {
                if (response.code === 200) {
                    this.friendList = response.data;
                }
            })
        },
        newFriendCellClick() {
            router.push({path: '/newfriend'})
        },
        searchUserChatList() {
            this.messageTotalNumber = 0
            searchUserChatList(this.user.userId).then(response => {
                if (response.code === 200) {
                    this.chatFriendList = response.data
                    response.data.forEach(item => {
                        this.messageTotalNumber += item.unreadMessageCount
                        if (this.messageTotalNumber > 100) {
                            this.messageTotalNumber = '99+'
                        } else if (this.messageTotalNumber > 1000) {
                            this.messageTotalNumber = '999+'
                        }
                    })
                }
            })
        },
        toChatWith(userId) {
            router.push(
                {
                    name: 'chatwindow',
                    params: {
                        friendUserId: userId
                    }
                }
            )
        },
        changeToTopStatus(friendUserId) {
            let requestParam = [this.user.userId, friendUserId];
            changeToTopStatus(requestParam).then(response => {
                if (response.code === 200) {
                    this.searchUserChatList()
                }
            })
        },
        changeChatListDeleteStatus(friendUserId) {
            let requestParam = [this.user.userId, friendUserId];
            changeChatListDeleteStatus(requestParam).then(response => {
                if (response.code === 200) {
                    this.searchUserChatList()
                }
            })
        },
        getNewMessage(res) {
            let messageObj = JSON.parse(res)
            if (this.tabbarActive === 0) {
                this.searchUserChatList()
            } else {
                Notify({
                    message: `${messageObj.nickname}的新消息`,
                    type: 'primary',
                    duration: 1500,
                });
            }
        }
    },
    created() {
        this.user = JSON.parse(sessionStorage.getItem("user"));
        this.whetherHaveNewFriend()
        this.searchUserChatList()
        if (!websocketReadyState()) {
            initWebSocket()
        }
        getSock(this.getNewMessage)
    }
}
</script>

<style scoped>
/deep/ .van-image {
    margin-top: 4px;
}

.van-card {
    background-color: white;
    --van-card-padding: 10px;
    --van-card-thumb-size: 45px;
    --van-card-thumb-magin-top: 10px;
    --van-card-thumb-border-radius: 50%;
    --van-card-font-size: 17px;
    --van-card-title-line-height: 25px;
    --van-card-price-color: #646566;
}

/deep/ .van-card-header {
    background-color: rgb(0, 174, 239);
    --van-card-padding: 10px;
    --van-card-thumb-size: 45px;
    --van-card-thumb-magin-top: 10px;
    --van-card-thumb-border-radius: 50%;
    --van-card-font-size: 17px;
    --van-card-title-line-height: 30px;
    --van-card-price-color: #646566;
    --van-card-price-integer-font-size: 12px
}

/deep/ .van-multi-ellipsis--l2 {
    font-weight: 550;
}

/deep/ .van-ellipsis {
    font-size: 13px;
}

/deep/ .van-card__num {
    font-size: 13px;
}

.van-tabs {
    --van-tabs-bottom-bar-color: rgb(0, 174, 239);
}

.custom-title {
    margin-right: 4px;
    vertical-align: middle;
}

hr {
    background-color: #d4d4d4;
    color: #d4d4d4;
    height: 1px;
    border: 0;
    clear: both;
}

.delete-button {
    height: 100%;
}
</style>